package com.googlecode.marrowboy.matchers;

import java.util.regex.Pattern;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

/**
 * Hamcrest matcher for checking if a {@link String} fits a {@link Pattern} (ie
 * a regex). This class uses {@link java.util.regex.Matcher#find()} and
 * {@link Pattern#MULTILINE} so the effect is rather like Unix egrep.
 * 
 * @author mjg
 */
public class RegexMatcher extends TypeSafeMatcher<String> {

	private final Pattern pattern;

	/**
	 * Convenience constructor.
	 * 
	 * @param pattern
	 *            regex as a {@link String}.
	 */
	public RegexMatcher(String pattern) {
		if (pattern == null) {
			this.pattern = null;

		} else {
			this.pattern = Pattern.compile(pattern, Pattern.MULTILINE);

		}
	}

	/**
	 * Constructor.
	 * 
	 * @param pattern
	 *            {@link Pattern} to match.
	 */
	public RegexMatcher(Pattern pattern) {
		this.pattern = pattern;
	}

	/**
	 * appends the description of this matcher to the {@link Description}.
	 * 
	 * @param description
	 *            the {@link Description} to append to.
	 */
	public void describeTo(Description description) {
		description.appendText("a string matching regular expression ").appendValue(pattern);
	}

	/**
	 * Check whether the argument matches.
	 * 
	 * @param item
	 *            the {@link String} to check.
	 * 
	 * @return whether or not it was a match.
	 */
	@Override
	public boolean matchesSafely(String item) {

		if (item == null || pattern == null) {
			return false;
		}

		return pattern.matcher(item).find();
	}

}